#include "stdafx.h"
#include "TL_Libs_DB.h"

using namespace System;
using namespace System::Collections;
using namespace System::Data;
using namespace System::Data::SQLite;

namespace TL_Libs {

	
	Sqlite::Sqlite(String^ dbname)
	{
		this->_dbstring = "Data Source=" + dbname + ";Pooling=true;FailIfMissing=false";
	}

	Sqlite::~Sqlite()
	{
		//this->_conn->Close();
	}

	SQLiteCommand^ Sqlite::GetCommand(void)
	{
		String^ query = this->GetQuery();
		return this->GetCommand(query);;

	}

	SQLiteCommand^ Sqlite::GetCommand(String^ query)
	{
		this->_conn = gcnew SQLiteConnection(this->_dbstring);
		this->_conn->Open();

		SQLiteCommand^ cmd = gcnew SQLiteCommand();
		cmd->Connection::set(this->_conn);
		cmd->CommandText::set(query);
		return cmd;

	}

	int Sqlite::ExecuteQuery(void) 
	{
		SQLiteCommand^ cmd = this->GetCommand();
		int result = cmd->ExecuteNonQuery();

		this->_conn->Close();

		return result;
	}

	Hashtable^ Sqlite::GetRow(int id) 
	{
		Hashtable^ result = gcnew Hashtable;
		
		this->Where("id = ", id.ToString());
		this->Limit("1");
		SQLiteCommand^ cmd = this->GetCommand();
		SQLiteDataReader^ dr = cmd->ExecuteReader(CommandBehavior::CloseConnection);
		if (dr->Read())
		{
			result = this->_GetRow(dr);
		}
		this->_conn->Close();

		return result;
	}

	Hashtable^ Sqlite::GetRow(void) 
	{
		Hashtable^ result = gcnew Hashtable;

		this->Limit("1");
		SQLiteCommand^ cmd = this->GetCommand();
		SQLiteDataReader^ dr = cmd->ExecuteReader(CommandBehavior::CloseConnection);
		if (dr->Read())
		{
			result = this->_GetRow(dr);
		}
		this->_conn->Close();

		return result;
	}

	Hashtable^ Sqlite::_GetRow(SQLiteDataReader^ dr)
	{
		Hashtable^ result = gcnew Hashtable;
		for (int i=0; i<dr->FieldCount; ++i)
		{
			result->Add(dr->GetName(i), dr->GetValue(i));
		}
		return result;
	}

	ArrayList^ Sqlite::GetAll(void)
	{
		ArrayList^ result = gcnew ArrayList;

		SQLiteCommand^ cmd = this->GetCommand();
		SQLiteDataReader^ dr = cmd->ExecuteReader(CommandBehavior::CloseConnection);
		while (dr->Read())
		{
			Hashtable^ item = this->_GetRow(dr);
			result->Add(item);
		}
		this->_conn->Close();

		return result;
	}

	int Sqlite::GetInsertId(void)
	{
		Hashtable^ result = gcnew Hashtable;

		String^ query = "Select last_insert_rowid() AS insert_id";
		SQLiteCommand^ cmd = this->GetCommand(query);
		SQLiteDataReader^ dr = cmd->ExecuteReader(CommandBehavior::CloseConnection);
		if (dr->Read())
		{
			result = this->_GetRow(dr);
		}
		this->_conn->Close();

		if (result->ContainsKey("insert_id"))
		{
			return Convert::ToInt32(result["insert_id"]);
		}
		return 0;
	}

	String^ Sqlite::safeValue(String^ string)
	{
		return string->Replace("'", "''");
	}

	String^ Sqlite::parseValue(String^ string)
	{
		return string->Replace("''", "'");
	}

}